package cube.utils.exec;

import cube.utils.TimeUtil;

/**
 * 条件式阻塞执行器
 * 
 * @author abiao
 */
public abstract class BlockExecutor<R> {

	/**
	 * 阻塞周期时间
	 */
	private static final int BLOCK_PERIOD = 10;

	/**
	 * 阻塞执行
	 */
	public R blockExecute() {
		while (!condition()) {
			TimeUtil.blockPeriod();
		}
		return action();
	}

	/**
	 * 超时阻塞执行
	 */
	public R blockExecute(int timeout) {
		for (int i = 0; i < timeout / BLOCK_PERIOD; i++) {
			if (condition()) {
				return action();
			}
			TimeUtil.blockPeriod();
		}
		if (condition()) {
			return action();
		}
		TimeUtil.sleep(timeout % BLOCK_PERIOD);
		return action();
	}

	/**
	 * 执行动作
	 */
	public abstract R action();

	/**
	 * 执行条件
	 */
	public abstract boolean condition();
}
